import React, { useState } from 'react'
import type { FC } from 'react'
import {
  Button,
  DatePicker,
  Form,
  Input,
  InputNumber,
  Radio,
  Cascader,
  Flex,
  Upload,
  message
} from 'antd'
import type { FormProps, UploadProps } from 'antd'
import { UploadOutlined } from '@ant-design/icons'
import dayjs from 'dayjs'
import { rangeDayOrYearToDate, readerFile } from '@/utils/tools'
import {
  checkUserExistApi,
  uploadUserAvatarApi,
  addUserApi
} from '@/services/userApi'

interface IProps {
  changeVisiable: (show: boolean) => void
}

const UserAdd: FC<IProps> = ({ changeVisiable }) => {
  const [form] = Form.useForm()
  const [img, setImg] = useState('')
  const [avatar, setAvatar] = useState('')
  // 获取指定年数的哪一天的日期
  const [dateString, dateObject] = rangeDayOrYearToDate(-20)
  const onFinish: FormProps<IUserType.IUserForm>['onFinish'] = async (
    values
  ) => {
    values = {
      ...values,
      avatar,
      birthday: (values.birthday as unknown as dayjs.Dayjs).format('YYYY-MM-DD')
    }
    let ret = await addUserApi(values)
    if (ret.code == 0) {
      form.resetFields()
      setAvatar('')
      setImg('')
      changeVisiable(false)
    } else {
      message.error('新增用户失败', 3)
    }
  }
  const onFinishFailed: FormProps<IUserType.IUserForm>['onFinishFailed'] = (
    errorInfo
  ) => {}

  // 点击上传
  const onBeforeUpload: UploadProps['beforeUpload'] = async (file) => {
    // 只能上传10MB以下的图片
    const imgFileSize = 10 * 1024 * 1024
    if (file.size > imgFileSize) {
      message.error('上传的图片大小超过10MB', 3)
    }

    // 在当前页面回显
    // file对象在img中显示出来
    const imgBaseUrl = (await readerFile(file, 3)) as string
    setImg(imgBaseUrl)

    // 通过FormData对象完成上传
    const formData = new FormData()
    formData.append('file', file)
    // 网络请求发送
    let avatarRet = await uploadUserAvatarApi(formData)
    // 设置一下上传头像的在服务器端的相对地址
    setAvatar(avatarRet.data.filepath)

    return Promise.reject()
  }

  return (
    <>
      <Form
        form={form}
        labelCol={{ span: 4 }}
        wrapperCol={{ span: 16 }}
        initialValues={{ age: 23, sex: 1, birthday: dateObject }}
        onFinish={onFinish}
        onFinishFailed={onFinishFailed}
        autoComplete="off"
      >
        <Form.Item
          label="账号"
          name="username"
          validateTrigger="onBlur"
          rules={[
            {
              required: true,
              whitespace: true,
              message: '账号不能为空！'
            },
            {
              validator: async (rule, value: string | undefined) => {
                // 只有username表单项有值，才进行账号唯一性验证
                if (value) {
                  let ret = await checkUserExistApi(value)
                  if (ret.data == 0) {
                    return Promise.resolve()
                  }
                  return Promise.reject('账号已存在')
                }
                return Promise.reject()
              }
            }
          ]}
        >
          <Input />
        </Form.Item>
        <Form.Item
          label="姓名"
          name="realname"
          rules={[
            {
              required: true,
              whitespace: true,
              message: '姓名不能为空'
            }
          ]}
        >
          <Input />
        </Form.Item>
        <Form.Item
          label="密码"
          name="password"
          rules={[
            {
              required: true,
              whitespace: true,
              message: '密码不能为空'
            }
          ]}
        >
          <Input />
        </Form.Item>
        <Form.Item label="年龄" name="age">
          <InputNumber min={18} max={100} />
        </Form.Item>
        <Form.Item label="性别" name="sex">
          <Radio.Group>
            <Radio value={1}> 先生 </Radio>
            <Radio value={2}> 女士 </Radio>
          </Radio.Group>
        </Form.Item>
        <Form.Item label="地址" name="address">
          <Input />
        </Form.Item>
        <Form.Item label="生日" name="birthday">
          <DatePicker style={{ width: 300 }} />
        </Form.Item>
        <Form.Item
          label="籍贯"
          name="city"
          rules={[
            {
              validator: (rule, value: undefined | string[]) => {
                if (!value) {
                  return Promise.reject('籍贯不能为空')
                }
                return Promise.resolve()
              }
            }
          ]}
        >
          <Cascader
            style={{ width: 300 }}
            options={[
              {
                label: '北京',
                value: '北京',
                children: [
                  {
                    label: '昌平',
                    value: '昌平'
                  },
                  {
                    label: '顺义',
                    value: '顺义'
                  }
                ]
              },
              {
                label: '安徽',
                value: '安徽',
                children: [
                  {
                    label: '合肥',
                    value: '合肥'
                  },
                  {
                    label: '芜湖',
                    value: '芜湖'
                  }
                ]
              }
            ]}
            placeholder="请选择城市"
          />
        </Form.Item>
        <Form.Item label="头像" name="avatar">
          <div>
            <Upload action="" beforeUpload={onBeforeUpload} fileList={[]}>
              <Button icon={<UploadOutlined />}>点击上传头像</Button>
            </Upload>
            <img src={img} style={{ width: 100 }} />
          </div>
        </Form.Item>
        <Form.Item wrapperCol={{ offset: 4, span: 16 }}>
          <Flex gap="small">
            <Button type="primary" htmlType="submit">
              新增用户信息
            </Button>
            <Button>重置表单</Button>
          </Flex>
        </Form.Item>
      </Form>
    </>
  )
}

export default UserAdd
